package com.gitee.feizns.quickstart.validation.validator;

import com.gitee.feizns.dynamic.Objs;
import com.gitee.feizns.quickstart.validation.constraints.NotContainsNull;

import javax.validation.ConstraintValidatorContext;
import java.util.Arrays;
import java.util.Collection;
import java.util.Objects;
import java.util.stream.Stream;

/**
 * 验证数组或者集合中是否包含{@code null}
 * <p>
 *    用于对数组，或者是集合的验证。
 *    如果数组或者集合中包含{@code null}
 *    则会返回相应的错误消息
 * </p>
 * @author feizns
 * @since 2019/7/24
 */
public class NotContainsNullConstraintValidator extends AbstractConstraintValidator<NotContainsNull, Object> {

    @SuppressWarnings("unchecked")
    @Override
    public boolean isValid(Object value, ConstraintValidatorContext context) {
        Stream<Object> values = Stream.empty();
        if ( Objs.isArray(value) )
            values = Arrays.stream(Objs.toArray(value));
        else if ( value instanceof Collection )
            values = ((Collection<Object>) value).stream();
        return values.noneMatch(Objects::isNull);
    }

}
